// 获取表格数据
$(function () {
    var TableInstence; // 表格实例
    var TableId;        // 当前表格id
    var DelTableId;     // 要删除的表格id
    var MergeSetting; // 合并配置
    var StyleSetting = {
        "all": {"color": "black", "background-color": "white"},
        "cells": {},
        "class": {}
    }; // 颜色配置

    $('#myModal').modal({backdrop: 'static', keyboard: false});
// 是否可编辑
    var isedit;
    var editor = $("#is_edit").text();
    if (editor == 1) {
        isedit = true
    } else {
        isedit = false
    }

    function isnum(str) {
        return str.search(/^[0-9]+$/i) != -1;
    }

// 渲染器
    function firstRowRenderer(instance, td, row, col, prop, value, cellProperties) {
        Handsontable.renderers.TextRenderer.apply(this, arguments);
        //以下只是设置格子的样式 color，backgroundColor，textAlign，fontSize等css样式都可以使用，大家自由发挥 背景还可以透明"transparent"
        var allstyle = StyleSetting["all"];//获取全局样式
        var tconf = {}; //当前样式
        for (var sty in allstyle) {
            tconf[sty] = allstyle [sty];//拷贝全局样式
        }
        var cellconf = StyleSetting.cells[row + "_" + col];//获取指定格子的样式
        if (cellconf) {
            for (var sty in cellconf) {
                if (cellconf[sty]) {
                    tconf[sty] = cellconf[sty];
                }
            }
        }
        for (var sty in tconf) {
            td.style[sty] = tconf[sty];
        }

    }


// 修改事件
    function submit(changes) {
        var data = {
            modifi: $("#modifi").text(),
            data: TableInstence.getData(),
            style: StyleSetting,
            merge: MergeSetting.mergedCellsCollection.mergedCells
        };

        $.ajax({
            headers: {"X-CSRFToken": $.cookie('csrftoken')},
            url: '/teach/distribute/set/' + TableId + "/",
            type: "post",
            ContentType: "application/json",
            data: JSON.stringify(data),
            dataType: "json",
            success: function (data) {
                if (data.code === 200) {
                    $("#modifi").text(data.modifi);
                    $("#ps").text("已自动保存");
                } else {
                    $("#ps").text(data.error);
                }
                 var timer = setTimeout(function () {
                        $("#ps").text("");
                    }, 2000)
            }
        })
    };
    var example = document.getElementById('example1');
    TableInstence = new Handsontable(example, {
            height: $("#example1").height(), // 高度设置
            startRows: 30, // 初始行
            startCols: 30, // 初始列
            rowHeaders: true, // 行头
            colHeaders: true, // 列头
            manualColumnResize: true, // 允许列调整大小
            manualRowResize: true, // 允许行调整大小
            // manualColumnMove: true, // 允许列移动
            // manualRowMove: true, // 允许行移动
            bindRowsWithHeaders: true,
            contextMenu: true, // 展示菜单
            mergeCells: true, // 合并单元格

            beforeKeyDown: function (e) {
                // 禁止撤销功能, 颜色不跟着动
                if (e.keyCode === 90) {
                    return false
                }
            },

            headerTooltips: {
                rows: true,
                columns:
                    true,
                onlyTrimmed:
                    false
            }
            ,
            search: true,
            outsideClickDeselects:
                false,

            cells:

                function (row, col, prop) {
                    this.renderer = firstRowRenderer;
                }
        },
    );


    if (!isedit) {
        TableInstence.updateSettings(
            {
                editor: false
            }
        );
    }

    // 绑定合并单元格配置
    MergeSetting = TableInstence.getPlugin('mergeCells');

    // 菜单语言配置
    TableInstence.updateSettings(
        {
            language: "zh-CN"
        }
    );
    TableId = $(".sheet-name")[0].id;
    $($(".sheet-name")[0]).css("background", "#fff");
    $($(".sheet-name")[0]).next().css("background", "#fff");

    // 加载表格设置
    function get_data() {

        $.ajax({
            url: '/teach/distribute/get/' + TableId + "/",
            type: "get",
            dataType: "json",
            success: function (data) {
                $("#modifi").text(data.modifi);
                if (data.code == 200) {
                    // 加载数据

                    if (data.style) {
                        // 配置全局样式
                        StyleSetting = JSON.parse(data.style);
                    } else {
                        StyleSetting = {
                            "all": {"color": "black", "background-color": "white"},
                            "cells": {},
                            "class": {}
                        };
                    }
                    if (data.merge) {
                        // 配置单元格设置
                        var mergedata = JSON.parse(data.merge);
                        TableInstence.updateSettings({mergeCells: mergedata})
                    } else {
                        TableInstence.updateSettings({mergeCells: []})
                    }
                    if (data.data) {
                        TableInstence.loadData(JSON.parse(data.data));
                    } else {
                        TableInstence.clear()
                    }
                }

                // 等待加载完后注册变化事件
                TableInstence.updateSettings({afterChange: submit});

                // 注册菜单选项
                TableInstence.updateSettings({
                    contextMenu: {
                        items: {
                            'mergeCells': {},
                            addup_row: {
                                name: "<span><span>向上插入</span><input type=\"text\" id=\"beforeRowInput\" class=\"insert-row-col-input\" value=\"1\"><span>行</span></span>",
                                callback: function (e) {
                                    var addnum = $("#beforeRowInput").val();
                                    var selectStartRow = TableInstence.getSelected()[0][0]; // 选中的首行
                                    var i;
                                    var cells = {};
                                    for (i in StyleSetting.cells) { // 循环所有样式
                                        var row_col = i.split("_");
                                        var row = row_col[0]; //设置样式的行
                                        var col = row_col[1]; // 设置样式的列
                                        if (parseInt(row) >= parseInt(selectStartRow)) {
                                            cells[parseInt(row) + parseInt(addnum) + "_" + col] = StyleSetting.cells[i];
                                        } else {
                                            cells[i] = StyleSetting.cells[i];
                                        }
                                    }

                                    StyleSetting.cells = cells;
                                    TableInstence.alter("insert_row", selectStartRow, addnum);
                                }
                            },
                            add_down: {
                                name: "<span><span>向下插入</span><input type=\"text\" id=\"afterRowInput\" class=\"insert-row-col-input\" value=\"1\"><span>行</span></span>",
                                callback: function () {
                                    var addnum = $("#afterRowInput").val();
                                    var selectLastRow = TableInstence.getSelected()[0][2]; // 选定的最后一行
                                    var i;
                                    var cells = {};
                                    for (i in StyleSetting.cells) { // 循环所有样式
                                        var row_col = i.split("_");
                                        var row = row_col[0]; //设置样式的行
                                        var col = row_col[1]; // 设置样式的列
                                        if (parseInt(row) > parseInt(selectLastRow)) {
                                            cells[parseInt(row) + parseInt(addnum) + "_" + col] = StyleSetting.cells[i];
                                        } else {
                                            cells[i] = StyleSetting.cells[i];
                                        }
                                    }

                                    StyleSetting.cells = cells;
                                    TableInstence.alter("insert_row", selectLastRow + 1, addnum) // getSelected()[0] = [起始行, 起始列, 终止行, 终止列]
                                }
                            },
                            'col_left': {
                                name: "<span><span>向左插入</span><input type=\"text\" id=\"beforeColInput\" class=\"insert-row-col-input\" value=\"1\"><span>列</span></span>",
                                callback: function (e) {
                                    var addnum = $("#beforeColInput").val();
                                    var selectStartcol = TableInstence.getSelected()[0][1]; // 选中的首列
                                    var i;
                                    var cells = {};
                                    for (i in StyleSetting.cells) { // 循环所有样式
                                        var row_col = i.split("_");
                                        var row = row_col[0]; //设置样式的行
                                        var col = row_col[1]; // 设置样式的列
                                        if (parseInt(col) >= parseInt(selectStartcol)) {
                                            cells[parseInt(row) + "_" + (parseInt(col) + parseInt(addnum))] = StyleSetting.cells[i];
                                        } else {
                                            cells[i] = StyleSetting.cells[i];
                                        }
                                    }

                                    StyleSetting.cells = cells;
                                    TableInstence.alter("insert_col", TableInstence.getSelected()[0][1], addnum)
                                }
                            },
                            'col_right': {
                                name: "<span><span>向右插入</span><input type=\"text\" id=\"afterColInput\" class=\"insert-row-col-input\" value=\"1\"><span>列</span></span>",
                                callback: function (e) {
                                    var addnum = $("#afterColInput").val();
                                    var selectLastcol = TableInstence.getSelected()[0][3]; // 选中的尾列
                                    var i;
                                    var cells = {};
                                    for (i in StyleSetting.cells) { // 循环所有样式
                                        var row_col = i.split("_");
                                        var row = row_col[0]; //设置样式的行
                                        var col = row_col[1]; // 设置样式的列
                                        if (parseInt(col) > parseInt(selectLastcol)) {
                                            cells[parseInt(row) + "_" + (parseInt(col) + parseInt(addnum))] = StyleSetting.cells[i];
                                        } else {
                                            cells[i] = StyleSetting.cells[i];
                                        }
                                    }

                                    StyleSetting.cells = cells;
                                    TableInstence.alter("insert_col", TableInstence.getSelected()[0][3] + 1, addnum)
                                }
                            },
                            'remove_row': {},
                            'remove_col': {},
                            'copy': {},
                            'cut': {},
                            'make_read_only': {},
                        }
                    },
                });
                $('#myModal').modal('hide')
            }
        });
    };

    get_data();
    // 新增列之后
    TableInstence.addHook("afterCreateCol", function () {
        submit()
    });

    // 新增行之后
    TableInstence.addHook("afterCreateRow", function () {
        submit()
    });

    // 移除列之后
    TableInstence.addHook("afterRemoveCol", function (index, amount, physicalRows, source) {
        // index 起始行
        // amount 移除的行数
        var cells = {};
        for (i in StyleSetting.cells) { // 循环所有样式
            var row_col = i.split("_");
            var row = row_col[0]; //设置样式的行
            var col = row_col[1]; // 设置样式的列
            // 指定区域内容全部删除, 后面内容填充
            if (parseInt(col) >= index && parseInt(col) < index + amount) {
                // 删除指定区域内容, 直接不设置
                // cells[parseInt(row) + parseInt(addnum) + "_" + col] = StyleSetting.cells[i];
            } else if (parseInt(col) >= index + amount) {
                // 颜色上移
                cells[row + "_" + (parseInt(col) - amount)] = StyleSetting.cells[i];
            } else {
                cells[i] = StyleSetting.cells[i];
            }
        }

        StyleSetting.cells = cells;
        submit()
    });

    // 移除行之后
    TableInstence.addHook("afterRemoveRow", function (index, amount, physicalRows, source) {
        // index 起始行
        // amount 移除的行数
        var cells = {};
        for (i in StyleSetting.cells) { // 循环所有样式
            var row_col = i.split("_");
            var row = row_col[0]; //设置样式的行
            var col = row_col[1]; // 设置样式的列
            // 指定区域内容全部删除, 后面内容填充
            if (parseInt(row) >= index && parseInt(row) < index + amount) {
                // 删除指定区域内容, 直接不设置
                // cells[parseInt(row) + parseInt(addnum) + "_" + col] = StyleSetting.cells[i];
            } else if (parseInt(row) >= index + amount) {
                // 颜色上移
                cells[parseInt(row) - amount + "_" + col] = StyleSetting.cells[i];
            } else {
                cells[i] = StyleSetting.cells[i];
            }
        }

        StyleSetting.cells = cells;
        submit()
    });

    // 拖拽事件
    TableInstence.addHook("beforeAutofill", function (start, end, data) {
        var localdata = TableInstence.getData();
        var startRow = start.row; // 起始行
        var startCol = start.col; // ,起始列
        var endRow = end.row; // 终止行,
        var endCol = end.col; // 终止列
        for (var i = startCol; i <= endCol; i++) { // 循环列
            var startdata = localdata[startRow - 1][i];
            for (var j = startRow; j <= endRow; j++) { // 循环行
                if (isnum(startdata.toString())) {
                    data.push([++startdata]);
                } else {
                    var aa = new Date(startdata);
                    if (aa.toString() != "Invalid Date") {
                        aa.setDate(aa.getDate() + 1);
                        data.push([aa.toLocaleString().split(" ")[0]]);
                        startdata = aa.toLocaleString().split(" ")[0]
                    } else {
                        data.push([startdata]);
                    }
                }
            }
        }
        data.shift();
    });

    // 菜单点开后
    TableInstence.addHook('afterContextMenuShow', function (context) {
        $(".htContextMenu").on("mouseenter", "input", function (e) {
            $(this).val("");
            this.focus();
        })
    });

    // 选中单元格
    TableInstence.addHook('afterSelectionEnd', function (context) {
        $("#select_cell").val(TableInstence.getActiveEditor().TD.textContent)
    });
    // 颜色选择事件
    $(".color-set").on("click", ".color-picker-rect", function () {
        $(this).parent().parent().parent().parent().prev().css("background", $(this).css("background"));
        $(this).parent().parent().parent().parent().prev().prev().click()
    });

// 修改背景颜色设置
    $("#background").on("click", function () {
        var color = $(this).next().css("background-color");
        selected = TableInstence.getSelectedRange()[0];
        var from = selected.from;
        var to = selected.to;
        for (var i = from.row; i <= to.row; i++) {
            for (var j = from.col; j <= to.col; j++) {
                $(TableInstence.getCell(i, j)).css("background", color);
                if (StyleSetting.cells[i + "_" + j]) {
                    StyleSetting.cells[i + "_" + j]["background"] = color;
                } else {
                    StyleSetting.cells[i + "_" + j] = {"background": color};
                }

            }
        }
        submit()
    });

// 修改字体颜色设置
    $("#color").on("click", function () {
        var color = $(this).next().css("background-color");
        selected = TableInstence.getSelectedRange()[0];
        var from = selected.from;
        var to = selected.to;
        for (var i = from.row; i <= to.row; i++) {
            for (var j = from.col; j <= to.col; j++) {
                $(TableInstence.getCell(i, j)).css("color", color);
                if (StyleSetting.cells[i + "_" + j]) {
                    StyleSetting.cells[i + "_" + j]["color"] = color;
                } else {
                    StyleSetting.cells[i + "_" + j] = {"color": color};
                }
            }
        }
        submit()
    });

// 左对齐事件
    $("#htLeft").on("click", function () {
        selected = TableInstence.getSelectedRange()[0];
        var from = selected.from;
        var to = selected.to;
        for (var i = from.row; i <= to.row; i++) {
            for (var j = from.col; j <= to.col; j++) {
                $(TableInstence.getCell(i, j)).css("text-align", "left");
                if (StyleSetting.cells[i + "_" + j]) {
                    StyleSetting.cells[i + "_" + j]["text-align"] = "left";
                } else {
                    StyleSetting.cells[i + "_" + j] = {"text-align": "left"};
                }
            }
        }
        submit()
    });

// 右对齐事件
    $("#htRight").on("click", function () {
        selected = TableInstence.getSelectedRange()[0];
        var from = selected.from;
        var to = selected.to;
        for (var i = from.row; i <= to.row; i++) {
            for (var j = from.col; j <= to.col; j++) {
                $(TableInstence.getCell(i, j)).css("text-align", "right");
                if (StyleSetting.cells[i + "_" + j]) {
                    StyleSetting.cells[i + "_" + j]["text-align"] = "right";
                } else {
                    StyleSetting.cells[i + "_" + j] = {"text-align": "right"};
                }
            }
        }
        submit()
    });

// 两端对齐事件
    $("#htJustify").on("click", function () {
        selected = TableInstence.getSelectedRange()[0];
        var from = selected.from;
        var to = selected.to;
        for (var i = from.row; i <= to.row; i++) {
            for (var j = from.col; j <= to.col; j++) {
                $(TableInstence.getCell(i, j)).css("text-align", "justify");
                if (StyleSetting.cells[i + "_" + j]) {
                    StyleSetting.cells[i + "_" + j]["text-align"] = "justify";
                } else {
                    StyleSetting.cells[i + "_" + j] = {"text-align": "justify"};
                }
            }
        }
        submit()
    });

// 居中对齐事件
    $("#htCenter").on("click", function () {
        selected = TableInstence.getSelectedRange()[0];
        var from = selected.from;
        var to = selected.to;
        for (var i = from.row; i <= to.row; i++) {
            for (var j = from.col; j <= to.col; j++) {
                $(TableInstence.getCell(i, j)).css("text-align", "center");
                if (StyleSetting.cells[i + "_" + j]) {
                    StyleSetting.cells[i + "_" + j]["text-align"] = "center";
                } else {
                    StyleSetting.cells[i + "_" + j] = {"text-align": "center"};
                }
            }
        }
        submit()
    });

// 垂直居中事件
    $("#htMiddle").on("click", function () {
        selected = TableInstence.getSelectedRange()[0];
        var from = selected.from;
        var to = selected.to;
        for (var i = from.row; i <= to.row; i++) {
            for (var j = from.col; j <= to.col; j++) {
                $(TableInstence.getCell(i, j)).css("vertical-align", "middle");
                if (StyleSetting.cells[i + "_" + j]) {
                    StyleSetting.cells[i + "_" + j]["vertical-align"] = "middle";
                } else {
                    StyleSetting.cells[i + "_" + j] = {"vertical-align": "middle"};
                }
            }
        }
        submit()
    });

// 顶部对齐事件
    $("#htTop").on("click", function () {
        selected = TableInstence.getSelectedRange()[0];
        var from = selected.from;
        var to = selected.to;
        for (var i = from.row; i <= to.row; i++) {
            for (var j = from.col; j <= to.col; j++) {
                $(TableInstence.getCell(i, j)).css("vertical-align", "top");
                if (StyleSetting.cells[i + "_" + j]) {
                    StyleSetting.cells[i + "_" + j]["vertical-align"] = "top";
                } else {
                    StyleSetting.cells[i + "_" + j] = {"vertical-align": "top"};
                }
            }
        }
        submit()
    });

// 底部对齐事件
    $("#htBottom").on("click", function () {
        selected = TableInstence.getSelectedRange()[0];
        var from = selected.from;
        var to = selected.to;
        for (var i = from.row; i <= to.row; i++) {
            for (var j = from.col; j <= to.col; j++) {
                $(TableInstence.getCell(i, j)).css("vertical-align", "bottom");
                if (StyleSetting.cells[i + "_" + j]) {
                    StyleSetting.cells[i + "_" + j]["vertical-align"] = "bottom";
                } else {
                    StyleSetting.cells[i + "_" + j] = {"vertical-align": "bottom"};
                }
            }
        }
        submit()
    });

// 加宽事件
    $("#Weight").on("click", function () {
        selected = TableInstence.getSelectedRange()[0];
        var from = selected.from;
        var to = selected.to;
        for (var i = from.row; i <= to.row; i++) {
            for (var j = from.col; j <= to.col; j++) {

                if (StyleSetting.cells[i + "_" + j]) {
                    if (StyleSetting.cells[i + "_" + j]["font-weight"] === "bold") {
                        StyleSetting.cells[i + "_" + j]["font-weight"] = "normal";
                        $(TableInstence.getCell(i, j)).css("font-weight", "normal");
                    } else {
                        StyleSetting.cells[i + "_" + j]["font-weight"] = "bold";
                        $(TableInstence.getCell(i, j)).css("font-weight", "bold");
                    }
                } else {
                    StyleSetting.cells[i + "_" + j] = {"font-weight": "bold"};
                    $(TableInstence.getCell(i, j)).css("font-weight", "bold");
                }
            }
        }
        submit()
    });

// 斜体事件
    $("#Font_style").on("click", function () {
        selected = TableInstence.getSelectedRange()[0];
        var from = selected.from;
        var to = selected.to;
        for (var i = from.row; i <= to.row; i++) {
            for (var j = from.col; j <= to.col; j++) {

                if (StyleSetting.cells[i + "_" + j]) {
                    if (StyleSetting.cells[i + "_" + j]["font-style"] === "normal") {
                        StyleSetting.cells[i + "_" + j]["font-style"] = "italic";
                        $(TableInstence.getCell(i, j)).css("font-style", "italic");
                    } else {
                        StyleSetting.cells[i + "_" + j]["font-style"] = "normal";
                        $(TableInstence.getCell(i, j)).css("font-style", "normal");
                    }
                } else {
                    StyleSetting.cells[i + "_" + j] = {"font-style": "italic"};
                    $(TableInstence.getCell(i, j)).css("font-style", "italic");
                }
            }
        }
        submit()
    });

// 下划线事件
    $("#Text_decoration").on("click", function () {
        selected = TableInstence.getSelectedRange()[0];
        var from = selected.from;
        var to = selected.to;
        for (var i = from.row; i <= to.row; i++) {
            for (var j = from.col; j <= to.col; j++) {

                if (StyleSetting.cells[i + "_" + j]) {
                    if (StyleSetting.cells[i + "_" + j]["text-decoration"] === "underline") {
                        StyleSetting.cells[i + "_" + j]["text-decoration"] = 'none';
                        $(TableInstence.getCell(i, j)).css("text-decoration", 'none');
                    } else {
                        StyleSetting.cells[i + "_" + j]["text-decoration"] = "underline";
                        $(TableInstence.getCell(i, j)).css("text-decoration", "underline");
                    }
                } else {
                    StyleSetting.cells[i + "_" + j] = {"text-decoration": "underline"};
                    $(TableInstence.getCell(i, j)).css("text-decoration", "underline");
                }
            }
        }
        submit()
    });

    $("#add-sheet").on("click", function () {
        $('#myModal').modal('show');
        for (var i = 0; i < $(".sheet-manu").length; i++) {
            $($(".sheet-manu")[i]).css("background", "#f7f7f7")
        }
        $.ajax({
            headers: {"X-CSRFToken": $.cookie('csrftoken')},
            url: '/teach/distribute/add_sheet/',
            type: "post",
            ContentType: "application/json",
            dataType: "json",
            success: function (data) {
                // $("#sheet-tab").append('<div style="display: inline-block;"><div class="btn-group dropup"><button type="button" class="btn btn-default sheet-tab sheet-name sheet-manu" id="' + data.id + '"><input type="text" class="rename-input" style="display: none"><span>' + data.name + '</span></button><button type="button" class="btn btn-default dropdown-toggle sheet-tab sheet-manu sheet-list" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"><span class="caret"></span><span class="sr-only">Toggle Dropdown</span></button><ul class="dropdown-menu"><li><span class="del-sheet">删除</span></li><li><span class="rename">重命名</span></li></ul></div></div>')
                $("#sheet-tab").append('<div style="display: inline-block;" ><div class="btn-group dropup"><button type="button" style="background:#fff" class="btn btn-default sheet-list sheet-name sheet-manu" id="' + data.id + '"><input class="rename-input" type="text" style="display:none"><span>' + data.name + '</span></button><button type="button" style="background:#f7f7f7" class="btn btn-default dropdown-toggle sheet-manu" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"><span class="caret"></span><span class="sr-only">Toggle Dropdown</span></button><ul class="dropdown-menu"><li><span class="del-sheet">删除</span></li><li><span class="rename">重命名</span></li></ul></div></div>')
                TableId = data.id;
                $("#modifi").text(data.modifi);
                TableInstence.updateSettings({
                    afterChange: function () {

                    }
                });
                get_data();

            }
        });
    });

    $("#sheet-tab").on("click", ".rename-input", function () {
        return false
    });
    $("#sheet-tab").on("click", ".sheet-list", function () {
        $('#myModal').modal('show');
        for (var i = 0; i < $(".sheet-manu").length; i++) {
            $($(".sheet-manu")[i]).css("background", "#f7f7f7")
        }
        TableId = this.id;
        TableInstence.updateSettings({
            afterChange: function () {

            }
        });
        get_data();
        $(this).css("background", "#fff");
        $(this).next().css("background", "#fff")
    });

    $("#sheet-tab").on("click", ".del-sheet", function () {
        if ($(".sheet-list").length == 1) {
            layer.alert('最后一张表格禁止删除')
        } else {
            DelTableId = $(this).parent().parent().prev().prev()[0].id;

            layer.confirm('确定删除该工作区?', {
                btn: ['确认', '取消'] //按钮
            }, function () {
                $.ajax({
                    headers: {"X-CSRFToken": $.cookie('csrftoken')},
                    url: '/teach/distribute/del/' + DelTableId + "/",
                    type: "post",
                    dataType: "json",
                    success: function (data) {
                        if (data.code != 400) {
                            if (DelTableId != TableId) {
                                $("#" + DelTableId).parent().parent().remove();
                                layer.msg("删除成功", {icon: 1});
                            } else {
                                $('#myModal').modal('show');
                                $("#" + DelTableId).parent().parent().remove();
                                TableId = $(".sheet-name")[0].id;
                                $($(".sheet-name")[0]).css("background", "#fff");
                                $($(".sheet-name")[0]).next().css("background", "#fff");
                                TableInstence.updateSettings({
                                    afterChange: function () {
                                    }
                                });
                                get_data();
                                layer.msg("删除成功", {icon: 1});
                            }
                            layer.msg("删除成功", {icon: 1});
                        } else {
                            layer.alert(data.error)
                        }
                    }
                });

            }, function () {
                // layer.msg('也可以这样', {
                //     time: 20000, //20s后自动关闭
                //     btn: ['明白了', '知道了']
                // });
            });
        }

    });

    $("#sheet-tab").on("click", ".rename", function () {

        $(this).parent().parent().prev().prev().css("padding", "0px");
        var input = $(this).parent().parent().prev().prev().children()[0];
        var span = $(this).parent().parent().prev().prev().children()[1];
        $(input).val($(span).text());
        $(input).css("display", "block");
        $(input).css("width", parseInt($(span).css("width"))+24 +"px");
        $(span).css("display", "none")
    });
    $("#sheet-tab").on("blur", ".rename-input", function () {
        var name = $(this).val();
        var editid = $(this).parent()[0].id;
        var _this = this;
        $.ajax({
            headers: {"X-CSRFToken": $.cookie('csrftoken')},
            url: '/teach/distribute/rename/' + editid + "/",
            type: "post",
            data: {"name": name},
            dataType: "json",
            success: function (data) {
                if (data.code != 400) {
                    if (editid == TableId) {
                        $("#modifi").text(data.modifi);
                    }
                    $(_this).css("display", "none");
                    $(_this).css("width", "");
                    $(_this).next().text(data.name);
                    $(_this).next().css("display", "block");
                    $("#ps").text("已自动保存");
                    var timer = setTimeout(function () {
                        $("#ps").text("");
                    }, 2000)
                    $(_this).parent().css("padding", "6px 12px")
                } else {
                    layer.alert(data.error);
                    $(_this).css("display", "none");
                    $(_this).css("width", "");
                    $(_this).val($(_this).next().text());
                    $(_this).next().css("display", "block");
                    $(_this).parent().css("padding", "6px 12px")
                }
            }
        });


    })
})
;
